/**
 * Copyright 2018 orivil.com. All rights reserved.
 * Use of this source code is governed by a MIT-style
 * license that can be found at https://mit-license.org.
 */

package oauth2

import (
	"github.com/google/go-querystring/query"
	"net/http"
)

// 初始化微信登陆地址
// scope 分两种, 一种是 "snsapi_base", 只能根据返回的 code 换取用户的 openid, 另一种是 "snsapi_userinfo", 能够根据返回的
// code 换取用户的所有信息.
// uri 为用户授权后所跳转的地址, 且该地址会自动添加上 code 及 state 参数
// appid 为微信公众号的配置
// state 为用户自定义参数
func InitRedirect(s scope, uri, appid, state string) string {
	u, _ := query.Values(&redirectConfig{
		AppID:        appid,
		RedirectUri:  uri,
		ResponseType: "code",
		Scope:        s,
		State:        state,
	})
	return "https://open.weixin.qq.com/connect/oauth2/authorize?" + u.Encode() + "#wechat_redirect"
}

// 用户授权后跳转至指定的 URI 时会带上, code 及 state 参数
func GetUriCode(req *http.Request) (code, state string) {
	q := req.URL.Query()
	return q.Get("code"), q.Get("state")
}

type redirectConfig struct {
	AppID        string `url:"appid"`
	RedirectUri  string `url:"redirect_uri"`
	ResponseType string `url:"response_type"`
	Scope        scope  `url:"scope"`
	State        string `url:"state"`
}